/*
 * DataEngine.h
 *
 *  Created on: 2021
 *      Author:ysy
 */

#ifndef DATAENGINE_H_
#define DATAENGINE_H_
using namespace std;
#include <string>
#include <iostream>

#include <thread>
#include <ctime>
#include <map>
#include <set>
#include <vector>
#include "ThreadPool.h"
#include "future_tick.h"
#include <sys/timeb.h>
#include <set>
#include <map>
#include <unordered_map>
class BaseStrategy;
#include "strategy/BaseStrategy.h"
#include "spinlock.h"
using namespace std;
class DataEngine
{
private:

    mutex mtx;
    unique_ptr<Disruptor<Event,DefaultRingBufferSize>> eventBuffers[4];
    unordered_map<string,Disruptor<Event,DefaultRingBufferSize>*> contractBufferMap;
    unordered_map<Disruptor<Event,DefaultRingBufferSize>*,set<BaseStrategy*>> bufferStrategyMap;
    DataEngine();
    DataEngine(const DataEngine&) = delete; // 禁止拷贝构造
    DataEngine& operator=(const DataEngine&) = delete; // 禁止拷贝赋值
    int strategyId=0;
public:
     double  InitialBp=0;
    bool isTrading = false;
    unsigned int traderDay=0;
    long lastOffset=0;
    string traderTime;
    bool isStop= false;
    static DataEngine* getInstancePtr();
    long int now{};//当前毫秒数
    atomic<int>   m_MaxToken{0};
    int maxStrategyId=0;
    map<string,DoubleDeque> enterTime_map;
    int getNextToken();
    int getCurrentToken();
	std::set<string>  m_contracts;
    unordered_map<string,json> contractMap;
    unordered_map<string,atomic_int> informationMap;

	map<int,BaseStrategy*> strategies;
    unordered_map<string,BaseStrategy*> strategyMap;
	unordered_map<string, set<BaseStrategy*>> con_strategy_maps;

    Disruptor<ReqOrderMsg,DefaultRingBufferSize> udpBuffer;

	virtual ~DataEngine();
    void delStrategy(BaseStrategy* p_strategy);
    int getNextStrategyId();
	void processSymbolStatusReport(EES_SymbolStatus *pSymbolStatus);

	void processQrySymbolStatusReport(EES_SymbolStatus *pSymbolStatus, bool bFinish);

	void PthreadBindCore(int core_id);


	void startAllStrategy();

	void stopAllStrategy();
	//获取当前的毫秒 从1970年开始
	static long  getNanoTime();


    void udpOrderHandel(ReqOrderMsg& orderMsg);


	void addStrategy(int index,BaseStrategy* p_strategy);

	void saveCancelMap();
	void loadCancelMap();

	void resetCancelMap();

	void resetPosition();

    void addEvent(Event& event);
    void startEngine();
    //void startEngine1();
    void initEngine();
    void loadContracts();
    static int getIndexOfContract(const string & s);

    static long calculateTime(int hour,int minute,int second);

    bool static mdIsEffective(const TickDataHf &md0, const TickDataHf &md1);

    static double formatDouble(double price);

    string getMaxStrategyId();
};

#endif /* DATAENGINE_H_ */
